package com.ai.hear;

import com.ai.analysis.StoreHouse;
import com.base.SnThread;
import com.iflytek.cloud.speech.SpeechConstant;
import com.iflytek.cloud.speech.SpeechError;
import com.iflytek.cloud.speech.SpeechUnderstander;
import com.iflytek.cloud.speech.SpeechUnderstanderListener;
import com.iflytek.cloud.speech.TextUnderstander;
import com.iflytek.cloud.speech.TextUnderstanderListener;
import com.iflytek.cloud.speech.UnderstanderResult;

/**
 * @Description 语义听写
 * @ClassName UnderstaOperator
 * @Date 2017年8月10日 下午3:07:11
 * @Author yanghao Copyright (c) All Rights Reserved, 2017.
 */
public class UnderstaOperator extends SnThread {

	private SpeechUnderstander understander;

	public UnderstaOperator() {
		// 1.创建文本语义理解对象
		this.understander = SpeechUnderstander.createUnderstander();
		// 2.设置参数
		this.understander.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
		this.understander.startUnderstanding(mUnderstanderListener);
		
		//
		mTextUnderstander = TextUnderstander.createTextUnderstander();
	}

	// XmlParser为结果解析类，见SpeechDemo
	private SpeechUnderstanderListener mUnderstanderListener = new SpeechUnderstanderListener() {
		public void onResult(UnderstanderResult result) {
			String text = result.getResultString();
			//System.out.println("uop = " + text);
			StoreHouse.addRaw(text);
			goon();
		}

		public void onError(SpeechError error) {
			goon();
		}// 会话发生错误回调接口

		public void onBeginOfSpeech() {
		}// 开始录音

		public void onVolumeChanged(int volume) {
			if (volume == 0)
				volume = 1;
			else if (volume >= 6)
				volume = 6;
		} // 音量值0~30

		public void onEndOfSpeech() {
		}// 结束录音

		public void onEvent(int eventType, int arg1, int arg2, String msg) {
		}// 扩展用接口
	};

	private boolean goon = true;

	private void goon() {
		if (this.goon) {
			this.understander.startUnderstanding(mUnderstanderListener);
		} else {
			this.understander.stopUnderstanding();
		}
	}
	
	//
	//创建文本语义理解对象
	TextUnderstander mTextUnderstander = null; 
	//初始化监听器
	TextUnderstanderListener searchListener = new TextUnderstanderListener(){
		//语义结果回调
		public void onResult(UnderstanderResult result){
			String text = result.getResultString();
			//System.out.println("uop txt = " + text);
			StoreHouse.addRaw(text);
		}
		//语义错误回调
		public void onError(SpeechError error) {}
	}; 

	public void addTxt(String inStr) {
		mTextUnderstander.understandText(inStr, searchListener);
	}

}
